$(function() {
	'use strict';

	var console = window.console || {
		log: function() {}
	};
	var $image = $('#image');
	var $dataX = $('#dataX');
	var $dataY = $('#dataY');
	var $dataHeight = $('#dataHeight');
	var $dataWidth = $('#dataWidth');
	var $dataRotate = $('#dataRotate');
	var $dataScaleX = $('#dataScaleX');
	var $dataScaleY = $('#dataScaleY');
	var options = {
		aspectRatio: 1 / 1,
		preview: '.img-preview',
		crop: function(e) {
			$dataX.val(Math.round(e.x));
			$dataY.val(Math.round(e.y));
			$dataHeight.val(Math.round(e.height));
			$dataWidth.val(Math.round(e.width));
			$dataRotate.val(e.rotate);
			$dataScaleX.val(e.scaleX);
			$dataScaleY.val(e.scaleY);
		},
		minContainerWidth: 715,
		minContainerHeight: 350
	};

	// Tooltip
	$('[data-toggle="tooltip"]').tooltip();

	// Cropper
	$image.on().cropper(options);

	// Buttons
	if(!$.isFunction(document.createElement('canvas').getContext)) {
		$('button[data-method="getCroppedCanvas"]').prop('disabled', true);
	}

	if(typeof document.createElement('cropper').style.transition === 'undefined') {
		$('button[data-method="rotate"]').prop('disabled', true);
		$('button[data-method="scale"]').prop('disabled', true);
	}

	// Options
	$('.docs-toggles').on('change', 'input', function() {
		var $this = $(this);
		var name = $this.attr('name');
		var type = $this.prop('type');
		var cropBoxData;
		var canvasData;

		if(!$image.data('cropper')) {
			return;
		}

		if(type === 'checkbox') {
			options[name] = $this.prop('checked');
			cropBoxData = $image.cropper('getCropBoxData');
			canvasData = $image.cropper('getCanvasData');

			options.built = function() {
				$image.cropper('setCropBoxData', cropBoxData);
				$image.cropper('setCanvasData', canvasData);
			};
		} else if(type === 'radio') {
			options[name] = $this.val();
		}

		$image.cropper('destroy').cropper(options);
	});

	// Methods
	$('.docs-buttons').on('click', '[data-method]', function() {
		var $this = $(this);
		var data = $this.data();
		var $target;
		var result;

		if($this.prop('disabled') || $this.hasClass('disabled')) {
			return;
		}

		if($image.data('cropper') && data.method) {
			data = $.extend({}, data); // Clone a new one

			if(typeof data.target !== 'undefined') {
				$target = $(data.target);

				if(typeof data.option === 'undefined') {
					try {
						data.option = JSON.parse($target.val());
					} catch(e) {
						console.log(e.message);
					}
				}
			}

			if(data.method === 'rotate') {
				$image.cropper('clear');
			}

			result = $image.cropper(data.method, data.option, data.secondOption);

			if(data.method === 'rotate') {
				$image.cropper('crop');
			}

			switch(data.method) {
				case 'scaleX':
				case 'scaleY':
					$(this).data('option', -data.option);
					break;

				case 'getCroppedCanvas':
					if(result) {
						uploadToServer($image, result);
					}
					break;
				case 'showCanvas':
					$('#getCroppedCanvasModal').modal('show');
			}

			if($.isPlainObject(result) && $target) {
				try {
					$target.val(JSON.stringify(result));
				} catch(e) {
					console.log(e.message);
				}
			}

		}
	});

	// Keyboard
	$(document.body).on('keydown', function(e) {

		if(!$image.data('cropper') || this.scrollTop > 300) {
			return;
		}

		switch(e.which) {
			case 37:
				e.preventDefault();
				$image.cropper('move', -1, 0);
				break;

			case 38:
				e.preventDefault();
				$image.cropper('move', 0, -1);
				break;

			case 39:
				e.preventDefault();
				$image.cropper('move', 1, 0);
				break;

			case 40:
				e.preventDefault();
				$image.cropper('move', 0, 1);
				break;
		}

	});

	// Import image
	var $inputImage = $('#inputImage');
	var URL = window.URL || window.webkitURL;
	!URL ? $('#filePicker').addClass('active') : '';
	var blobURL;
	$inputImage.change(function(e) {
		if(URL) {
			var files = this.files;
			var file;
			if(!$image.data('cropper')) {
				return;
			}
			file = files[0];
			if(file.size > 2097152) {
				messageinfo('文件大小超出限制')
				return;
			}
			if(files && files.length) {
				if(/^image\/\w+$/.test(file.type) || /\.(jpg|jpeg|png|gif)$/.test(file.name)) {
					blobURL = URL.createObjectURL(file);
					$image.one('built.cropper', function() {
						// Revoke when load complete
						URL.revokeObjectURL(blobURL);
					}).cropper('reset').cropper('replace', blobURL);
					$inputImage.val('');
				} else {
					window.alert('Please choose an image file.');
				}
			}

		} else {

		}
	});

	function dataURLtoBlob(dataurl) {
		var arr = dataurl.split(','),
			mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]),
			n = bstr.length,
			u8arr = new Uint8Array(n);
		while(n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		return new Blob([u8arr], {
			type: mime
		});
	}

	function messageinfo(text) {
		$('.messageinfo').text(text).addClass('move');
		setTimeout(function(){
			$('.messageinfo').removeClass('move')
		}, 1000);
	}

	function uploadToServer($image, result) {
		//  $image.cropper('getCroppedCanvas').toBlob(function (blob) {
		var formData = new FormData();
		var blob = dataURLtoBlob(result.toDataURL());
		formData.append("file", blob);
		$.ajax('../../../user/userinfo/uploadUserPhoto.json', {
			method: "POST",
			data: formData,
			processData: false,
			contentType: false,
			success: function(data) {
				messageinfo('上传成功');
				var data = data.data;
				var updatePhotoSet = ['#userPhotoUpload img', '#userPhotoCount img', '#user-photo img'];
				_.each(updatePhotoSet, function(item, index) {
					$(item).attr("src", "../../../components/gtattachment/open/downloadAttachment.json?attachmentId=" + data.attachid)
				})
				$('#getCroppedCanvasModal').modal('hide');
			},
			error: function() {
				console.log('Upload error');
			}
		});
	}
})